// 上传须知模态框控制
document.addEventListener('DOMContentLoaded', () => {
    // 初始化事件监听
    document.querySelector('.help-icon-wrapper').addEventListener('click', showModal);
    document.querySelector('.close-icon').addEventListener('click', closeModal);
    document.getElementById('modal-overlay').addEventListener('click', (e) => {
        if (e.target === document.getElementById('modal-overlay')) closeModal();
    });

    // 初始化上传组件
    initUploader('upload-1', 'dropzone-1', 'preview-1', 'file-info-1');
    initUploader('upload-2', 'dropzone-2', 'preview-2', 'file-info-2');

    // 绑定按钮事件
    document.getElementById('compare-btn').addEventListener('click', handleCompare);
    document.getElementById('reset-btn').addEventListener('click', resetAll);
});

/* 文件上传功能 */
function initUploader(uploadId, dropzoneId, previewId, fileInfoId) {
    const uploadInput = document.getElementById(uploadId);
    const dropzone = document.getElementById(dropzoneId);
    const preview = document.getElementById(previewId);
    const fileInfo = document.getElementById(fileInfoId);

    // 点击上传区域
    dropzone.addEventListener('click', () => uploadInput.click());

    // 拖拽处理
    const handleDrag = (e) => {
        e.preventDefault();
        dropzone.classList[e.type === 'dragover' ? 'add' : 'remove']('dragover');
    };

    dropzone.addEventListener('dragover', handleDrag);
    dropzone.addEventListener('dragleave', handleDrag);
    dropzone.addEventListener('drop', (e) => {
        handleDrag(e);
        handleFile(e.dataTransfer.files[0]);
    });

    // 文件选择处理
    uploadInput.addEventListener('change', (e) => handleFile(e.target.files[0]));

    function handleFile(file) {
        if (!file) return;

        // 增强文件验证
        const validTypes = ['image/jpeg', 'image/png', 'image/jpg'];
        if (!validTypes.includes(file.type)) {
            showToast('⚠️ 仅支持 JPG/PNG/JPEG 格式文件', 3000);
            return;
        }

        if (file.size > 5 * 1024 * 1024) {
            showToast('⚠️ 图片大小超过5MB限制', 3000);
            return;
        }

        // 更新界面
        dropzone.classList.add('has-file');
        const reader = new FileReader();
        reader.onload = (e) => {
            preview.src = e.target.result;
            preview.style.display = 'block';
            fileInfo.textContent = `${file.name} (${(file.size/1024/1024).toFixed(2)}MB)`;
        };
        reader.readAsDataURL(file);
    }
}

/* 人脸比对处理 */
async function handleCompare() {
    const files = [
        document.getElementById('upload-1').files[0],
        document.getElementById('upload-2').files[0]
    ];

    if (!files[0] || !files[1]) {
        showToast('请先上传两张图片', 3000);
        return;
    }

    let closeLoadingToast = showToast('🔄 正在上传并比对中...', 0); // 持续显示

    try {
        // 并行上传文件
        const [res1, res2] = await Promise.all([
            uploadFileWithProgress(files[0], 1),
            uploadFileWithProgress(files[1], 2)
        ]);

        // 执行比对
        const compareRes = await fetch('/api/compare_faces', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ image1: res1.url, image2: res2.url })
        });

        if (!compareRes.ok) {
            const error = await compareRes.json();
            throw new Error(error.message || '比对请求失败');
        }

        const result = await compareRes.json();
        closeLoadingToast();
        showToast(`✅ 比对成功！相似度：${result.confidence.toFixed(2)}%`, 5000);

    } catch (error) {
        closeLoadingToast();
        console.error('Error:', error);
        showToast(`❌ 操作失败: ${error.message}`, 5000);
    }
}

/* 增强版文件上传（带进度提示）*/
async function uploadFileWithProgress(file, index) {
    let closeUploadToast = showToast(`📤 正在上传第 ${index} 张图片...`, 0);

    try {
        const formData = new FormData();
        formData.append('file', file);

        const response = await fetch('/api/upload_face', {
            method: 'POST',
            body: formData
        });

        if (!response.ok) {
            const error = await response.json();
            throw new Error(error.message || '上传失败');
        }

        closeUploadToast();
        showToast(`✅ 第 ${index} 张图片上传成功`, 2000);
        return await response.json();

    } catch (error) {
        closeUploadToast();
        throw error;
    }
}

/* 重置功能 */
function resetAll() {
    document.querySelectorAll('.upload-zone').forEach(zone => {
        zone.classList.remove('has-file');
        zone.querySelector('.preview-image').src = '';
        zone.querySelector('.preview-image').style.display = 'none';
        zone.querySelector('input[type="file"]').value = '';
        zone.querySelector('.file-info').textContent = '';
    });
    showToast('已重置所有内容', 2000);
}

/* 模态框控制 */
function showModal() {
    document.getElementById('modal-overlay').style.display = 'flex';
    document.addEventListener('keydown', handleEscape);
}

function closeModal() {
    document.getElementById('modal-overlay').style.display = 'none';
    document.removeEventListener('keydown', handleEscape);
}

function handleEscape(e) {
    if (e.key === 'Escape') closeModal();
}

/* 增强版Toast提示 */
let activeToastTimer = null;

function showToast(message, duration = 3000) {
    const toast = document.getElementById('toast');

    // 清除之前的提示
    if (activeToastTimer) {
        clearTimeout(activeToastTimer);
        toast.style.display = 'none';
    }

    // 更新内容
    toast.textContent = message;
    toast.className = 'toast'; // 重置样式
    toast.style.display = 'block';

    // 设置自动关闭
    if (duration > 0) {
        activeToastTimer = setTimeout(() => {
            toast.style.display = 'none';
        }, duration);
    }

    // 返回手动关闭方法
    return () => {
        clearTimeout(activeToastTimer);
        toast.style.display = 'none';
    };
}
